package ext;


import java.util.ArrayList;
import java.util.Arrays;

/**
 * 优酷土豆笔试题
 */
public class YoukuTestUtil extends Thread {

    /**
     * 函数求一元多项式的导数
     *
     * @param data 多项式非零项系数和指数
     * @return 整型数组
     */
    public static int[] derivative(int[] data) throws Exception {
        ArrayList<Integer> res = new ArrayList<Integer>();
        for (int i = 0; i < data.length; i = i + 2) {
            data[i] *= data[i + 1];
            data[i + 1]--;
            if (data[i] != 0) {
                res.add(data[i]);
                res.add(data[i + 1]);
            } else {
                if (data.length == 2) {
                    res.add(0);
                    res.add(0);
                }
            }
        }

        int[] r = new int[res.size()];
        for (int i = 0; i < r.length; ++i)
            r[i] = res.get(i);

        return r;
    }


    /**
     * 计算给定数组能够组成的最长等差数列
     *
     * @param intAr 数组
     * @return 最长等差数列
     */
    public static int calcAPLength(int[] intAr) throws Exception {
        Arrays.sort(intAr);
        int len = intAr.length;
        if (len < 3)
            return len;

        int res = 0;//存放全局最大值
        for (int i = 0; i < len; i++) {
            for (int j = i + 1; j < len; j++) {
                int now = j;//工作指针
                int local = 2;//存放局部最大值
                int delta = intAr[j] - intAr[i];//以第i和第j个数为起点的数列等差

                for (int k = j + 1; k < len; k++) {
                    if ((intAr[k] - intAr[now]) == delta) {
                        local = local + 1;
                        now = k;
                    }
                    if (intAr[k] - delta > intAr[now]) break;
                }
                res = Math.max(res, local);
            }
        }
        return res;
    }

    public static void main(String[] args) throws Exception {
        int[] data = {5, 0};
        System.out.println(Arrays.toString(derivative(data)));

        int[] intAr = {3, 8, 4, 5, 6, 2};
        System.out.println(calcAPLength(intAr));
    }
}
